<template>
  <div class="goods-sku">
    <dl v-for="(spec,idx) in goodsData.specs" :key="idx">
      <dt>{{spec.name}}</dt>
      <dd >
        <template v-for="value in spec.values" :key="value.name">
        <img :class='{selected:value.selected,disabled:value.disabled}' @click="clickSpecs(value,spec.values)" v-if="value.picture"  :alt="value.name" :src="value.picture">
        <span :class='{selected:value.selected,disabled:value.disabled}' @click="clickSpecs(value,spec.values)"  v-else>{{value.name}}</span>
        </template>
      </dd>
    </dl>

  </div>
</template>
<script>
import getPowerSet from '@/vender/power-set'
const spliter = '*'
// 根据skus数据得到路径字典对象
const getPathMap = (skus) => {
  const pathMap = {}
  skus.forEach(sku => {
    // 1. 过滤出有库存有效的sku
    if (sku.inventory) {
      // 2. 得到sku属性值数组 ['黑色','中国', '10cm']
      const specs = sku.specs.map(spec => spec.valueName)
      // 3. 得到sku属性值数组的子集
      //    [[''],['黑色'],['中国'],['10cm'],['黑色','中国'],... ]
      const powerSet = getPowerSet(specs)
      // 4. 设置给路径字典对象
      powerSet.forEach(set => {
        const key = set.join(spliter)
        if (pathMap[key]) {
          // 已经有key往数组追加
          pathMap[key].push(sku.id)
        } else {
          // 没有key设置一个数组
          pathMap[key] = [sku.id]
        }
      })
    }
  })
  return pathMap
}
const getSelectedArr = specs => {
  return specs.map(spec => {
  // 找到这个属性下用户的选择
    const value = spec.values.find(it => it.selected === true)
    return value ? value.name : undefined
  })
}
// 1.获取用户已经选中的条件selectedArr
// 2.对于每个按钮来说
// key= 在组合当前的按钮对应的条件（selectedArr+当前的按钮对应条件）
// 去字典中查：pathMap[key]
const updateDisableStatus = (pathMap, specs) => {
  const _selectedArr = getSelectedArr(specs)
  console.log('当前用户选择的条件是', _selectedArr)
  specs.forEach((spec, idx) => {
    const selectedArr = [..._selectedArr]
    spec.values.forEach(btn => {
      if (btn.name === selectedArr[idx]) { return }
      btn.disabled = !pathMap[btn.name]
      // 把30cm填入当前的选择
      selectedArr[idx] = btn.name
      const key = selectedArr.filter(v => v).join(spliter)
      // console.log('当前用户的选择条件是', selectedArr, key)
      btn.disabled = !pathMap[key]
    })
  })
}

// 根据skuId还原用户选中的规格
const initSelectedStatus = (goodsData, skuId) => {
  // 1.找到选中的具体规则
  const sku = goodsData.skus.find(sku => sku.id === skuId)
  // 2.设置对应的按钮的selected为true
  if (sku) {
    const selectArr = sku.specs.map(it => it.valueName)
    console.log('找到选中的具体规格', selectArr, sku)
    // ['黑色'，'中国'，'10cm']
    goodsData.specs.forEach((spec, idx) => {
      spec.values.forEach(value => {
        value.selected = (value.name === selectArr[idx])
      })
    })
  }
}
export default {
  name: 'GoodsSku',
  props: {
    goodsData: { type: Object, default: () => ({ specs: [], skus: [] }) },
    skuId: {
      type: String,
      default: ''
    }
  },

  setup (props, { emit }) {
    // 它是已选中：则从已选中-->改成-->未选中
    // 它是未选中：则把它的兄弟改成未选中，把它自己改成选中
    const clickSpecs = (value, values) => {
      if (value.disabled) return false
      if (value.selected) {
        value.selected = false // 已选中-》改成-》未选中
      } else {
        // 未选中
        values.forEach(it => (it.selected = false))
        // 把自己改成选中
        value.selected = true
        // 再次更新状态
      }
      updateDisableStatus(pathMap, props.goodsData.specs)
      // 通知父组件
      tryEmit()
    }
    // 通知父组件
    const tryEmit = () => {
      const sku = {}
      // 触发change事件将sku数据传递出去
      const curSelected = getSelectedArr(props.goodsData.specs)
      // 如果选完了参数curSelected.filter(v=>v) 去掉undefined
      if (curSelected.filter(v => v).length === curSelected.length) {
        const key = curSelected.join(spliter)
        const skuId = pathMap[key][0]
        const skuObj = props.goodsData.skus.find(it => it.id === skuId)
        console.log('选全了', skuId)
        sku.skuId = skuId
        sku.price = skuObj.price
        sku.oldPrice = skuObj.oldPrice
        sku.inventory = skuObj.inventory
        sku.specsText = curSelected.join(',')
      }
      emit('change', sku)
    }
    const pathMap = getPathMap(props.goodsData.skus)
    // 根据传入的skuId默认选中规格按钮
    initSelectedStatus(props.goodsData, props.skuId)
    // 组件初始化的时候更新禁用状态
    updateDisableStatus(pathMap, props.goodsData.specs)
    console.log(pathMap, '数据在这里')
    return { clickSpecs }
  }
}
</script>
<style scoped lang="less">
.sku-state-mixin () {
  border: 1px solid #e4e4e4;
  margin-right: 10px;
  cursor: pointer;
  &.selected {
    border-color: @xtxColor;
  }
  &.disabled {
    opacity: 0.6;
    border-style: dashed;
    cursor: not-allowed;
  }
}
.goods-sku {
  padding-left: 10px;
  padding-top: 20px;
  dl {
    display: flex;
    padding-bottom: 20px;
    align-items: center;
    dt {
      width: 50px;
      color: #999;
    }
    dd {
      flex: 1;
      color: #666;
      > img {
        width: 50px;
        height: 50px;
        .sku-state-mixin ();
      }
      > span {
        display: inline-block;
        height: 30px;
        line-height: 28px;
        padding: 0 20px;
        .sku-state-mixin ();
      }
    }
  }
}
</style>
